package LinkedList.Medium;

import DataStructures.ListNode;

import java.util.ArrayList;

public class LC0002 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ptr1 = l1, ptr2 = l2;
        ListNode retHead = null, retPtr = null;
        int carry = 0;
        while (ptr1 != null || ptr2 != null) {
            int digitSum = (ptr1 != null ? ptr1.val : 0) + (ptr2 != null ? ptr2.val : 0) + carry;
            if (digitSum >= 10) {
                carry = 1;
                digitSum -= 10;
            } else {
                carry = 0;
            }

            if (retHead == null) {
                retHead = new ListNode(digitSum);
                retPtr = retHead;
            } else {
                retPtr.next = new ListNode(digitSum);
                retPtr = retPtr.next;
            }

            if (ptr1 != null) ptr1 = ptr1.next;
            if (ptr2 != null) ptr2 = ptr2.next;
        }

        if (carry == 1) retPtr.next = new ListNode(1);


        return retHead;
    }
}
